import base64
import json
import requests
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend


# 加密函数
def service_encrypt(word):
    key = b'ghThreeDataShare'
    iv = key  # IV与密钥相同
    plaintext = word.encode('utf-8')

    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
    encryptor = cipher.encryptor()

    padder = padding.PKCS7(algorithms.AES.block_size).padder()
    padded_data = padder.update(plaintext) + padder.finalize()

    encrypted = encryptor.update(padded_data) + encryptor.finalize()
    return base64.b64encode(encrypted).decode('utf-8')


# 解密函数
def service_decrypt(encrypted_str):
    key = b'ghThreeDataShare'
    iv = key
    ciphertext = base64.b64decode(encrypted_str)

    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
    decryptor = cipher.decryptor()

    decrypted_padded = decryptor.update(ciphertext) + decryptor.finalize()

    unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
    plaintext = unpadder.update(decrypted_padded) + unpadder.finalize()

    return plaintext.decode('utf-8')


# 调用获取Token接口
def get_token():
    # url = 'http://10.1.161.137:8080/ghThreeDataShare/auth/getToken'
    url = 'http://10.1.161.50:9082/ghThreeDataShare/auth/getToken'

    # 需要加密的参数（根据实际情况调整）
    data = {
        "key": "rMWaNPHG",
        "secret": "bcf56c05def96ea8a2a94cd011c40292e11c8dfe"
    }

    # 如果接口需要加密请求体，取消下面两行的注释
    # encrypted_data = city_service_encrypt(json.dumps(data))
    # response = requests.post(url, data=encrypted_data, headers={'Content-Type': 'text/plain'})

    # 如果接口不需要加密请求体，使用明文发送
    response = requests.post(url, json=data)

    if response.status_code == 200:
        result = response.json()
        if result.get('code') == 200:
            return result['msg']
        else:
            raise Exception(f"接口返回错误: {result.get('msg')}")
    else:
        raise Exception(f"HTTP请求失败: {response.status_code} - {response.text}")


# 调用业务接口示例: 获取船舶流量监测记录
def get_boat_flow_list(token, params):
    # url = 'http://10.1.161.137:8080/ghThreeDataShare/boatFlow/getBoatFlowList'
    url = 'http://10.1.161.50:9082/ghThreeDataShare/boatFlow/getBoatFlowList'

    params.update({
        "pageIndex": "1",
        "pageSize": "500"
    })
    encrypted_data = service_encrypt(json.dumps(params, ensure_ascii=False))

    headers = {'Authorization': token}
    data = {
        "key": "rMWaNPHG",
        "data": encrypted_data
    }

    response = requests.post(url, json=data, headers=headers)
    if response.status_code == 200:
        result = response.json()
        if result['code'] == 200:
            decrypted_data = service_decrypt(result['data'])
            return json.loads(decrypted_data)
        raise Exception(f"API call failed: {result['msg']}")
    response.raise_for_status()